package com.foreknow.elm.test;



import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Java中的反射机制
 * https://blog.csdn.net/weixin_52533007/article/details/123312217
 * 获取类Class的三种方式
 * 1. 对象名.getClass()
 * 2. Class.forName("完整路径")
 * 3. 类名.class
 */
public class ReflectionDemo {
    public void getNameTest() {
        String name = "fender";
        Class clazz = name.getClass();
        System.out.println("String的类的名称为:" + clazz.getName());
        Button button = new Button();
        Class clazz_btn = button.getClass();
        System.out.println("Button的类的名称为:" + clazz_btn.getName());
        Class superClass = clazz_btn.getSuperclass();
        System.out.println("Button父类的名称为:" + superClass.getName());
    }

    public String testMethod(String str, HashMap hashMap) {
        String returnStr = "当前方法要返回的结果";
        System.out.println("获取到HashMap中的数据" + hashMap.get("name") );
        return returnStr;
    }

    /**
     * 通过反射机制动态调用testMethod方法
     * 1. 获取类对象
     * 2. 获取方法：getMethod("方法名",你要获取方法参数的类型)
     * 3. 调用方法：invoke(你要调用方法所属的对象,参数)
     */
    public void getMethodTest() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获取类
        Class cls = Class.forName("com.foreknow.elm.test.ReflectionDemo");
        Class[] ptypes = new Class[2];
        ptypes[0] = Class.forName("java.lang.String");
        ptypes[1] = Class.forName("java.util.HashMap");
        //获取方法
        Method method = cls.getMethod("testMethod",ptypes);
        //调用方法
        HashMap map = new HashMap();
        map.put("name","test......");
        String result = (String) method.invoke(new ReflectionDemo(),"fender",map);
        System.out.println(result);
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        ReflectionDemo reflectionDemo = new ReflectionDemo();
        reflectionDemo.getMethodTest();
//        HashMap map = new HashMap();
//        map.put("name","test......");
//        String result = reflectionDemo.testMethod("fender",map);
//        System.out.println(result);
    }
}
